package com.lxk.config;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.lxk.service.event.EventBusEnum;
import com.lxk.service.event.EventBusManager;
import com.lxk.service.event.handler.ExceptionHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * Created by Lxk on 2020/7/25.
 */
@Configuration
public class EventBusConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Resource
    private EventBusManager eventBusManager;

    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue(1000);

    Executor taskExecutor = new ThreadPoolExecutor(5,20,10, TimeUnit.SECONDS,blockingQueue);


    @Bean
    public EventBus publishEventBus(){
        AsyncEventBus eventBus = new AsyncEventBus(taskExecutor,new ExceptionHandler()){
            @Override
            public String toString() {
                return EventBusEnum.EVENT_BUS_PUBLISH.getEventBusName();
            }
        };
        eventBus.register(this.applicationContext.getBean("blogPubEventHandler"));
        eventBus.register(this.applicationContext.getBean("commentPubHandler"));
        eventBus.register(this.applicationContext.getBean("visitEventHandler"));
        eventBus.register(this.applicationContext.getBean("otherEventHandler"));
        eventBusManager.put(EventBusEnum.EVENT_BUS_PUBLISH,eventBus);
        return eventBus;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
